package com.bigtotoro.shuiyincamera.editimage.fragment;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ViewFlipper;

import com.bigtotoro.shuiyincamera.BaseActivity;
import com.bigtotoro.shuiyincamera.R;
import com.bigtotoro.shuiyincamera.editimage.EditImageActivity;
import com.bigtotoro.shuiyincamera.editimage.ModuleConfig;
import com.bigtotoro.shuiyincamera.adapter.StickerAdapter;
import com.bigtotoro.shuiyincamera.model.StickerBean;
import com.bigtotoro.shuiyincamera.editimage.task.StickerTask;
import com.bigtotoro.shuiyincamera.editimage.utils.BitmapUtils;
import com.bigtotoro.shuiyincamera.editimage.view.StickerItem;
import com.bigtotoro.shuiyincamera.editimage.view.StickerView;
import com.bigtotoro.shuiyincamera.view.SelectPictureActivity;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 添加自定义图片水印
 *
 */
public class ImageStickerFragment extends BaseEditFragment implements OnClickListener {
    public static final int INDEX = ModuleConfig.INDEX_IMAGE_STICKER;

    public static final String TAG = ImageStickerFragment.class.getName();
    public static final String STICKER_FOLDER = "stickers";

    private View mainView;
    private ViewFlipper flipper;//ViewFlipper继承了fragment,
    private View backToMenu;// 返回主菜单
    private View backToType;// 返回类型选择
    private StickerView mStickerView;// 贴图显示控件
    private StickerAdapter mStickerAdapter;// 贴图列表适配器
    private LoadStickersTask mLoadStickersTask;
    private List<StickerBean> stickerBeanList = new ArrayList<StickerBean>();

    private SaveStickersTask mSaveTask;

    private ImageView inputPic;//要添加的水印图片，从相册选取

    public static ImageStickerFragment newInstance() {
        ImageStickerFragment fragment = new ImageStickerFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreateView(inflater,container,savedInstanceState);
        mainView = inflater.inflate(R.layout.fragment_image_water2,
                null);
        //loadStickersData();

        return mainView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        this.mStickerView = ensureEditActivity().mStickerView;//画布是存在的

        flipper = (ViewFlipper) mainView.findViewById(R.id.flipper);
        flipper.setInAnimation(activity, R.anim.in_bottom_to_top);
        flipper.setOutAnimation(activity, R.anim.out_bottom_to_top);

        //
        backToMenu = mainView.findViewById(R.id.back_to_main);
        inputPic = mainView.findViewById(R.id.input_pic);
        inputPic.setOnClickListener(this);
//        typeList = (RecyclerView) mainView
//                .findViewById(R.id.stickers_type_list);
//        typeList.setHasFixedSize(true);
//        LinearLayoutManager mLayoutManager = new LinearLayoutManager(activity);
//        mLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
//        typeList.setLayoutManager(mLayoutManager);
//        typeList.setAdapter(new StickerTypeAdapter(this));
        backToType = mainView.findViewById(R.id.back_to_type);// back按钮

//        stickerList = (RecyclerView) mainView.findViewById(R.id.stickers_list);
//        stickerList.setHasFixedSize(true);
//        LinearLayoutManager stickerListLayoutManager = new LinearLayoutManager(
//                activity);
//        stickerListLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
//        stickerList.setLayoutManager(stickerListLayoutManager);
//        mStickerAdapter = new StickerAdapter(this);
//        stickerList.setAdapter(mStickerAdapter);

        backToMenu.setOnClickListener(new BackToMenuClick());// 返回主菜单
        backToType.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {// 返回上一级列表
                flipper.showPrevious();
            }
        });


    }

    @Override
    public void onShow() {
        activity.mode =  EditImageActivity.MODE_IMAGE_STICKERS; //设置mode主要作用是返回和保存时起作用
        activity.mImageStickerFragment.getmStickerView().setVisibility(
                View.VISIBLE);
        activity.bannerFlipper.showNext();
        selectFromAblum();  //为了省略选择图片这一步，直接点击添加图片按钮就进入相册
    }

    @Override
    public void onShow(EditImageActivity activity) {
        ensureEditActivity();
        //activity是通过基类baseEditFragment的ensureEditActivity方法获取到的,其实就是getActivity
        //现在就是this有值，说明咱们的imageStickersFragment已经初始化了,但是基类的这个方法获取不到父类
        //activity是空的
        activity.mode = EditImageActivity.MODE_IMAGE_STICKERS;
        activity.mImageStickerFragment.getmStickerView().setVisibility(
                View.VISIBLE);//显示图片水印画布
        activity.bannerFlipper.showNext();//右上角菜单显示“应用”
    }

    @Override
    public void onShowNoNextMenu(EditImageActivity activity) {
        activity.mode =  EditImageActivity.MODE_IMAGE_STICKERS;;
        activity.mImageStickerFragment.getmStickerView().setVisibility(
                View.VISIBLE);
    }

    //导入贴图数据
    private void loadStickersData() {
        if (mLoadStickersTask != null) {
            mLoadStickersTask.cancel(true);
        }
        mLoadStickersTask = new LoadStickersTask();
        mLoadStickersTask.execute(1);
    }

    @Override
    public void onClick(View v) {
        if (v==inputPic){
            selectFromAblum();  //选择输入图片，点击进入相册
        }
    }
    /**
     * 从相册选择编辑图片
     */
    private void selectFromAblum() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            openAblumWithPermissionsCheck();
        } else {
            openAblum();
        }
    }

    public static final int REQUEST_PERMISSON_SORAGE = 1;
    public static final int REQUEST_PERMISSON_CAMERA = 2;
    public static final int SELECT_GALLERY_IMAGE_CODE = 7;
    public static final int TAKE_PHOTO_CODE = 8;
    public static final int ACTION_REQUEST_EDITIMAGE = 9;
    private void openAblum() {
        startActivityForResult(new Intent(
                        getActivity(), SelectPictureActivity.class),
                SELECT_GALLERY_IMAGE_CODE);
    }

    private void openAblumWithPermissionsCheck() {
        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    REQUEST_PERMISSON_SORAGE);
            return;
        }
        openAblum();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == REQUEST_PERMISSON_SORAGE
                && grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            openAblum();
            return;
        }//end if
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK) {
            // System.out.println("RESULT_OK");
            switch (requestCode) {
                case SELECT_GALLERY_IMAGE_CODE://相册返回
                    handleSelectFromAblum(data);

                    break;
            }// end switch
        }
    }
    private String path;
    private void handleSelectFromAblum(Intent data) {
        String filepath = data.getStringExtra("imgPath");
        path = filepath;
        /**
         * 拿到图片路径后，怎么将图片加载到mStickerView画布上？
         *
         */
        Bitmap bitmap = BitmapUtils.getSampledBitmap(path,200,200);
        
        mStickerView.addBitImage(bitmap);//将从相册选取的图片加载到画布上

        /**
         * 加载没问题，现在的问题是点击应用之后，图片失真
         * */
//        startLoadTask(); //异步载入图片
    }
    private void startLoadTask() {
        LoadImageTask task = new LoadImageTask();
        task.execute(path);
    }
    private Bitmap mainBitmap;
    private int mWidth = 200;//
    private int mHeight = 200;//
    /**
     * 这个方法是为了获取图片的，异步获取图片方法
     */
    private final class LoadImageTask extends AsyncTask<String, Void, Bitmap> {
        @Override
        protected Bitmap doInBackground(String... params) {
//            DisplayMetrics metrics = getResources().getDisplayMetrics();
//            mWidth = metrics.widthPixels / 2;
//            mHeight = metrics.heightPixels / 2;
            return BitmapUtils.getSampledBitmap(params[0],
                    mWidth / 4, mHeight / 4);
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }

        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        @Override
        protected void onCancelled(Bitmap result) {
            super.onCancelled(result);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            if (mainBitmap != null) {
                mainBitmap.recycle();
                mainBitmap = null;
                System.gc();
            }
            mainBitmap = result;
        }
    }// end inner

    /**
     * 导入贴图数据
     */
    private final class LoadStickersTask extends AsyncTask<Integer, Void, Void> {
        private Dialog loadDialog;

        public LoadStickersTask() {
            super();
            loadDialog = BaseActivity.getLoadingDialog(getActivity(), R.string.saving_image, false);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loadDialog.show();
        }

        @Override
        protected Void doInBackground(Integer... params) {
            stickerBeanList.clear();
            AssetManager assetManager = getActivity().getAssets();
            try {
                String[] lists = assetManager.list(STICKER_FOLDER);
                for (String parentPath : lists) {

                }//end for each
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }


        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            loadDialog.dismiss();
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            loadDialog.dismiss();
        }
    }//end inner class

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mLoadStickersTask != null) {
            mLoadStickersTask.cancel(true);
        }
    }

    /**
     * 跳转至贴图详情列表
     *
     * @param path
     */
    public void swipToStickerDetails(String path) {
        mStickerAdapter.addStickerImages(path);
        flipper.showNext();
    }

    /**
     * 从Assert文件夹中读取位图数据
     *
     * @param fileName
     * @return
     */
    private Bitmap getImageFromAssetsFile(String fileName) {
        Bitmap image = null;
        AssetManager am = getResources().getAssets();
        try {
            InputStream is = am.open(fileName);
            image = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }

    /**
     * 选择贴图加入到页面中
     *
     * @param path
     */
    public void selectedStickerItem(String path) {
//        mStickerView.addBitImage(getImageFromAssetsFile(path));
        mStickerView.addBitImage(mainBitmap);
    }

    public StickerView getmStickerView() {
        return mStickerView;
    }

    public void setmStickerView(StickerView mStickerView) {
        this.mStickerView = mStickerView;
    }

    /**
     * 返回主菜单页面
     *
     * @author panyi
     */
    private final class BackToMenuClick implements OnClickListener {
        @Override
        public void onClick(View v) {
            backToMain();
        }
    }// end inner class

    @Override
    public void backToMain() {
        mStickerView.clear();   //暂时不清空画布---2019/4/19
        activity.mode = EditImageActivity.MODE_NONE;
        activity.bottomGallery.setCurrentItem(MainMenuFragment.INDEX);
//        activity.bottomGallery.setCurrentItem(0);
        mStickerView.setVisibility(View.GONE);
        activity.mainImage.setVisibility(View.VISIBLE);

//        activity.bannerFlipper.setDisplayedChild(0); //默认0保存，1应用
        activity.bannerFlipper.showPrevious();
 //       if (activity.bitmap_list != null && activity.bitmap_list.size() > 0) {
//            Toast.makeText(activity, "长度===" + activity.bitmap_list.size(),
//                    Toast.LENGTH_SHORT).show();
//        }
    }

    /**
     * 保存贴图任务
     */
    private final class SaveStickersTask extends StickerTask {
        public SaveStickersTask(EditImageActivity activity) {
            super(activity);
        }

        /**
         * @param canvas //根据传入的bitmap生成的画布
         * @param m //根据mainImage计算出的矩阵
         */
        @Override
        public void handleImage(Canvas canvas, Matrix m) { // 添加的图片水印
            LinkedHashMap<Integer, StickerItem> addItems = mStickerView.getBank();// 获取每层贴图数据
            //拿到了所有的添加的图片水印
            for (Integer id : addItems.keySet()) {
                StickerItem item = addItems.get(id);
                item.matrix.postConcat(m);// 乘以底部图片变化矩阵,
//                item.matrix.preConcat(m);// 乘以底部图片变化矩阵,
                // postConcat相当于后乘，即 a=b×a
                //preConCat(b)相当于前乘,即 a=a×b
                canvas.drawBitmap(item.bitmap, item.matrix, null);
                //将水印图片保存到原图片中，每次获取到的都是最后刚刚添加的这个图片水印
            }
        }

        @Override
        public void handleImage2(Canvas canvas, Matrix m, int width, int height) {

        }

        @Override
        public void onPostResult(Bitmap result) {
            mStickerView.clear();   //暂时不清空画布---2019/4/19
            activity.changeMainBitmap(result,true);

            //将生成的bitmap保存在集合中
//            if (activity.bitmap_list != null && activity.bitmap_list.size() > 0) {
                //直接在这里将图片保存到内存中，不用到EditImageActivity中保存
//                BitmapUtils.writeImage(result,activity.saveFilePath,100);
//                activity.bitmap_list.add(result);
//            }
            backToMain();
        }

        @Override
        protected Bitmap doInBackground(Bitmap... bitmaps) {
            return null;
        }
    }

    /**
     * 点击应用按钮后，执行这个方法
     * 保存贴图层 合成一张图片
     * 循环执行这个方法？
     */
//    LinkedHashMap<Integer, StickerItem> addItems;
    public void applyStickers() {
        // System.out.println("保存 合成图片");
        if (mSaveTask != null) {
            mSaveTask.cancel(true);
        }
//        addItems = mStickerView.getBank();// 获取每层贴图数据
//        if (activity.bitmap_list != null && activity.bitmap_list.size() > 0) {
//            for (int i = 0; i < activity.bitmap_list.size(); i++) {
                //循环任务
                mSaveTask = new SaveStickersTask((EditImageActivity) getActivity());
                mSaveTask.execute(activity.getMainBit());//调用execute方法时传入AsynTask的第一个参数
//            }
//        } else {
//            mSaveTask = new SaveStickersTask((EditImageActivity) getActivity());
//            Bitmap bitmap = activity.getMainBit();
//            mSaveTask.execute(bitmap); //获取当前mainImage的背景bitmap
//        }
    }
}
